package mobao.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;

/**
 * 捕获pre,route和post里的异常
 * Created by yanghongquan on 2018/8/14 11:14
 */
public class ErrorFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        //限制仅处理来自Post的异常时,我的处理方式如下
        RequestContext rtx = RequestContext.getCurrentContext();
        ZuulFilter failedFilter = (ZuulFilter) rtx.get("failed.filter");
        if(failedFilter != null && "post".equals(failedFilter.filterType())){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("API网关的异常过滤器-"+ LocalDate.now());
        RequestContext cts = RequestContext.getCurrentContext();
        Throwable throwable = cts.getThrowable();
        System.out.println("this is a ErrorFilter:"+throwable.getCause().getMessage());
        cts.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        cts.set("error.exception", throwable.getCause());
        return null;
    }
}
